/**
 * Created by liupan on 2017-3-8.
 * 群组配置界面js
 * 对应JSP为hostgroup.jsp
 */
define(["require", "jquery", "public/app"], function (require, $, app) {

    function Hostgroup($container) {
        this._$container = $container;
        this._init();
    }

    Hostgroup.prototype._initUrlPath = function () {
        this.urlPaths = {
            listHostgroup: app.urlBuild("/dirms/monitor/group/all"),
            queryHostgroupType: app.urlBuild("/dirms/monitor/hostgroupType/queryHostgroupType"),
            listHostgroupType: app.urlBuild("/dirms/monitor/hostgroupType/all"),
            saveHostgroupAndTypeList: app.urlBuild("/dirms/monitor/hostgroupAndType/saveList"),
        }
    };

    Hostgroup.prototype._init = function () {
        this._initUrlPath();
        // this._initComponents();
        var self = this;
        var dataReady = app.getDataReady();

        dataReady.pushDataSource({//逐个放入所有数据源
            url: this.urlPaths.listHostgroup,
            key: 'HostgroupData'
        });

        dataReady.pushDataSource({//逐个放入所有数据源
            url: this.urlPaths.queryHostgroupType,
            key: 'HostgroupTypeData'
        });

        dataReady.once(function (readyData) {
            self._initComponents(readyData);
        });
    };

    Hostgroup.prototype._initComponents = function (readyData) {
        //初始化控件
        this._initHostgroupGrid(readyData);//初始化用户表格
        this._initEventBinding(this);//初始化事件绑定
        // this._initSearch();//初始化搜索
    };

    var HostgroupGrid;
    // Hostgroup.prototype._initSearch = function () {
    //     var self = this;
    //     //主表格搜索框
    //     $('#searchMenu').searchbox({
    //         //搜索功能未完成，应按照用户、角色、组织机构三类来进行搜索
    //         searcher: function (value, name) {
    //             if(name == 'name' && value != ""){
    //                 $.ajax({
    //                     type: "POST",
    //                     url: self.urlPaths.QueryHostgroupByName + value,
    //                     success:function(data){
    //                         if(data == ""||data == null){alert(value+" 模板不存在");}
    //                         else{
    //                             $('#hostgroupGrid').datagrid('loadData',data);
    //                             $('#searchMenu').searchbox('clear');
    //                         }
    //                     },
    //                     error:function(){alert("查询错误");}
    //                 });
    //             }
    //             // else{
    //             //     $('#_UserGrid').datagrid('reload');
    //             // }
    //         },
    //         menu: '#search',
    //         prompt: '请输入关键字'
    //     });
    // };
    //初始化表格
    Hostgroup.prototype._initHostgroupGrid = function (readyData) {
        var self = this;
        var hostgroupData = [];
        $.each(readyData.HostgroupData.data.result, function (index) {
            var hostgroupTypeData = readyData.HostgroupTypeData.data;
            var typeName = "",typeId = "",typeNote = "";
            if (hostgroupTypeData.hasOwnProperty(this.groupid)) {
                typeName = hostgroupTypeData[this.groupid].name;
                typeId = hostgroupTypeData[this.groupid].id;
                typeNote = hostgroupTypeData[this.groupid].note;
            }
            this.typeName = typeName;
            this.typeNameBak = typeName;
            this.typeNote = typeNote;
            this.typeId = typeId;
            hostgroupData.push(this);
        });

        self.editIndex = undefined;

        function onClickRow(index){
            if (self.editIndex != index){
                if (self._endEditHostgroup()){
                    $('#hostgroupGrid').datagrid('selectRow', index)
                        .datagrid('beginEdit', index);
                    self.editIndex = index;
                } else {
                    $('#hostgroupGrid').datagrid('selectRow', self.editIndex);
                }
            }
        }

        //主页面用户信息表格
        HostgroupGrid=$('#hostgroupGrid').datagrid({
            rownumbers: true,
            pagination: true,
            singleSelect: true,
            // fitColumns: true,
            // url: this.urlPaths.HostgroupData,
            data: hostgroupData,
            method: 'get',
            title: '',
            width: 'auto',
            height: '100%',
            region: 'south',
            //对应model层字段
            columns: [[
                {field:'groupid',title:"群组编号",width: '100'},
                {field: 'name', title: '群组名称', width: '200'},
                {field: 'typeName', title: '群组关联类型', width: '200', formatter: function (value, row, index) {
                    return row.typeNameBak;
                }, editor:{
                    type: 'combobox',
                    options: {
                        valueField: "id",
                        textField: "name",
                        method: 'get',
                        url: self.urlPaths.listHostgroupType,
                        editable: true,
                        required: true,
                        // formatter: function(value, row, index){
                        //     return value.name;
                        // }
                    }
                }},
            ]],
            toolbar: this._$container.find("#Toolbar"),
            onClickRow: onClickRow
        });
    };

    /**
     * 结束编辑模板
     */
    Hostgroup.prototype._endEditHostgroup = function () {
        var self = this;
        if (self.editIndex == undefined){return true}
        if ($('#hostgroupGrid').datagrid('validateRow', self.editIndex)){
            var ed = $('#hostgroupGrid').datagrid('getEditor', {index:self.editIndex,field:'typeName'});
            var name = $(ed.target).combobox('getText');
            var value = $(ed.target).combobox('getValue');
            $('#hostgroupGrid').datagrid('getRows')[self.editIndex]['typeName'] = name;
            $('#hostgroupGrid').datagrid('getRows')[self.editIndex]['typeNameBak'] = name;
            $('#hostgroupGrid').datagrid('getRows')[self.editIndex]['typeId'] = value;
            $('#hostgroupGrid').datagrid('endEdit', self.editIndex);
            self.editIndex = undefined;
            return true;
        } else {
            return false;
        }
    };


        /**
         * 事件绑定
         */
        Hostgroup.prototype._initEventBinding = function (self) {
            // this._$container.find('#edithostgroup_btn').on('click', {self: this}, this._actions.editHostgroupClick);
            this._$container.find('#accepthostgroup_btn').on('click', {self: this}, this._actions.acceptHostgroupClick);
            this._$container.find('#rejecthostgroup_btn').on('click', {self: this}, this._actions.rejectHostgroupClick);
        };


        /**
         * 在此定义此js用到的事件处理方法。如处理按钮click事件的方法
         * @type {{btcClick: Function}}
         */
        Hostgroup.prototype._actions = {
            //模板编辑按钮事件
            editHostgroupClick: function(evt){
                //获取这一行内容
                var row = $("#hostgroupGrid").datagrid('getSelections');
                if (row == undefined||row.length==0 ) {
                    $.messager.alert('提示',"请选择编辑对象",'info');
                    return;
                }else if(row.length>1){
                    $.messager.alert('提示',"只能选择单条记录",'info');
                    return;
                }
                showHostgroupDialog(evt,row);
            },
            acceptHostgroupClick: function (evt) {
                if (evt.data.self._endEditHostgroup()){
                    var changes = $('#hostgroupGrid').datagrid('getChanges');
                    var dataJson = [];
                    $.each(changes, function (index) {
                        var dataMap = {};
                        dataMap.typeId = this.typeId;
                        dataMap.hostgroupId = this.groupid;
                        dataJson.push(dataMap);
                    });

                    $.ajax({
                        url: evt.data.self.urlPaths.saveHostgroupAndTypeList,
                        type: "POST",
                        cache: false,
                        contentType: "application/json",
                        dataType: "json",
                        data : JSON.stringify(dataJson),
                        success: function(data){
                            $('#hostgroupGrid').datagrid('acceptChanges');
                            $.messager.alert('提示：','修改成功');
                        },
                        error: function () {
                            $('#hostgroupGrid').datagrid('rejectChanges');
                            evt.data.self.editIndex = undefined;
                            $.messager.alert('提示','修改失败！','info');
                        }
                    });
                }
            },
            rejectHostgroupClick: function (evt) {
                $('#hostgroupGrid').datagrid('rejectChanges');
                evt.data.self.editIndex = undefined;
            }
        };

        /**
         *
         * @param evt 点击时间
         * @param row  行记录数据
         */
        var showHostgroupDialog = function(evt,row){
            var inputUrl = evt.data.self.urlPaths.HostgroupEdit;
            var iconDataUrl = evt.data.self.urlPaths.IconsData;
            if (typeof(row) == 'undefined' || row.length != 1) {
                return;
            }
            var title="编辑模板";
            //对话框
            var templateEditdialog = $('<div id="template-edit"/>').dialog({
                title : title,
                top:100,
                width : 500,
                /*          height : 360,*/
                modal : true, //模式窗口：窗口背景不可操作
                resizable : false, //可拖动边框大小
                plain : true,
                href : inputUrl,
                buttons : [ {
                    text : '确定',
                    iconCls : 'icon-ok',
                    plain : true,
                    handler : function() {
                        var templateData = $("#templateEdit").serializeJsonStr();

                        var isValid = $('#templateEdit').form('validate');
                        if(!isValid){
                            return ;
                        }
                        $.ajax({
                            url:evt.data.self.urlPaths.UpdateHostgroupData,
                            type:"POST",
                            cache:false,
                            contentType: "application/json",
                            async : false,
                            dataType: "json",
                            data : templateData,
                            beforeSend:function(XMLHttpRequest){
                                $.messager.progress({
                                    title : '提示信息！',
                                    text : '数据处理中，请稍后....'
                                });
                            },
                            success: function(data){
                                $.messager.progress('close');
                                if(typeof(data) != "undefined" && data !=null && data!=''){
                                    $.messager.alert('提示','保存成功！','info');
                                    $("#hostgroupGrid").datagrid('reload');//重新加载列表数据
                                    $("#template-edit").dialog('destroy');//销毁对话框
                                }
                            },
                            error: function (event, XMLHttpRequest, ajaxOptions, thrownError) {
                                $.messager.progress('close');
                                $.messager.alert('提示','数据保存失败！','info')
                            }
                        });
                    }
                }, {
                    text : '取消',
                    iconCls : 'icon-cancel',
                    plain : true,
                    handler : function() {
                        $("#template-edit").dialog('destroy');//销毁对话框
                    }
                } ],
                onClose : function() {
                    $(this).dialog('destroy');
                },
                onLoad : function() {
                    /*user_input_form_init(evt);*/
                    //编辑
                    if(row != undefined && row.length==1){
                        // var id=row[0].id;
                        $("#icon").combobox({
                            url: iconDataUrl,
                            valueField: "value",
                            textField: "name",
                            method: 'get',
                            editable: true,
                            required: true,
                        });
                        $("#templateEdit").form("load",row[0]);
                        // $('#id').val(id);
                    }
                }
            }).dialog('open');
        };

        return Hostgroup;
    });
